package hng.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import hng.config.OssConfig;
import hng.enums.FileTypeEnum;
import hng.exception.BizException;
import hng.interceptor.LoginInterceptor;
import hng.model.FileInfoDO;
import hng.mapper.FileInfoMapper;
import hng.service.FileInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import hng.util.CommonUtil;
import hng.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 文件信息表 服务实现类
 * </p>
 *
 * @author 告白
 * @since 2024-06-27
 */
@Service
public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfoDO> implements FileInfoService {

    @Autowired
    private OssConfig ossConfig;

    /**
     * 上传单个文件
     */
    @Override
    public String uploadFile(MultipartFile file, String folderName) {
        OSS ossClient = null;
        try {
            // 获取原生文件名
            String originalFileName = file.getOriginalFilename();
            String folder = "village_cloud_shop/" + folderName;
            // 文件扩展名 .jpg、.doc
            String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
            String uuid = CommonUtil.getStringRandom(12);
            String folderUrl = folder + uuid + extension;
            // 获取相关配置
            String bucketName = ossConfig.getBucketName();
            String endpoint = ossConfig.getEndpoint();
            String accessKeyId = ossConfig.getAccessKeyId();
            String accessKeySecret = ossConfig.getAccessKeySecret();
            // 创建OSS对象
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, folderUrl, file.getInputStream());
            if (putObjectResult == null) {
                throw new BizException("文件上传异常");
            }
            String url = "https://" + ossConfig.getBucketName() + "." + endpoint + "/" + folderUrl;

            return url;
        } catch (Exception e) {
            throw new BizException("文件上传异常");
        } finally {
            // oss关闭服务，不然会造成ODM
            ossClient.shutdown();
        }
    }

    /**
     * 批量上传文件
     */
    @Override
    public List<String> uploadFiles(MultipartFile[] files, String folderName) {
        List<String> urls = new ArrayList<>();
        for (MultipartFile file : files) {
            String url = uploadFile(file, folderName);
            urls.add(url);
        }
        return urls;
    }
}
